const fs = require("fs");
const { DATA_PATH, DOMAN, PORT, LX, LY } = require("../config/config.default.js");
const { getOptical } = require("../services/opticals.service.js");
class File {
    constructor(fileName) {
        this.fileName = fileName;
    }
    async readFile() {
        return new Promise((resolve, reject) => {
            try {
                fs.readFile(this.fileName, 'utf-8', (err, data) => {
                    if (err) {
                        resolve([]);
                    } else {
                        if (data == "") {
                            data = JSON.stringify({ sites: [] });
                        }
                        let temp = JSON.parse(data);
                        if (temp['sites']) {
                            let rs = JSON.parse(JSON.stringify(temp['sites']));
                            resolve(rs)
                        } else {
                            resolve([]);
                        }
                    }
                })
            } catch (error) {
                console.log(error);
                resolve([]);
            }

        })
    }
    async writeFile(content) {
        return new Promise((resolve, reject) => {
            try {
                if (!content || content == "" || content == undefined) {
                    content = JSON.stringify({});
                } else {
                    content = JSON.stringify({ sites: content });
                }
                fs.writeFile(this.fileName, content, (err) => {
                    if (err) {
                        resolve(false);
                    } else {
                        resolve(true)
                    }
                })
            } catch (error) {
                console.log(error);
                resolve(false);
            }
        })
    }
    async eraseFile() {
        return new Promise((resolve, reject) => {
            try {
                fs.unlink(this.fileName, err => {
                    if (err) {
                        resolve(true);
                    } else {
                        resolve(false);
                    }
                })
            } catch (error) {
                console.log(error);
                resolve(false);
            }

        })
    }
    getIdx(keyName) {
        if (!keyName || keyName == "" || keyName == undefined) {
            return -1;
        }
        for (var k in this.modules) {
            if (this.modules[k][keyName] == "") {
                return k;
            }
        }
        return -1;
    }
    async getValue() {
        try {
            let obj = await this.readFile();
            if (Object.keys(obj).length == 0) {
                resolve([])
            } else {
                if (Object.keys(obj.sites)) {
                    resolve(obj.sites)
                } else {
                    resolve([])
                }
            }
        } catch (error) {
            resolve([]);
        }
    }
}


class Gzgj extends File {
    constructor(fileName) {
        super(fileName);
    }
    async settingAlarm({ gaojing }) {
        try {
            if (gaojing instanceof Object && Object.keys(gaojing).length > 0) {
                let arr = await this.readFile();
                let temp = JSON.parse(JSON.stringify(gaojing));
                if (arr instanceof Array && arr.length > 0) {
                    let sw = false;
                    for (var i = 0; i < arr.length; i++) {
                        //如果列表中的Show_Name与参数中的Show_Name相同，则替换，如果没有相同的，则添加
                        if (arr[i]['Show_Name'] == gaojing['Show_Name']) {
                            temp['Name'] = arr[i]['Name'];
                            arr.splice(i, 1, temp);
                            sw = true;
                            break;
                        }
                    }
                    //如果sw为false，说明没有相同的记录，那么重新添加
                    if (!sw) {
                        temp['Name'] = `BP_POI_GZGJ${arr.length}`;
                        arr.push(temp)
                    }
                } else {
                    arr = [];
                    temp['Name'] = `BP_POI_GZGJ${arr.length}`;
                    arr.push(temp)
                }
                let rs = await this.writeFile(arr);
                if (rs) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (error) {
            console.log(error);
            return true;
        }
    }
    async resetClick() {
        try {
            var list = await this.readFile();
            let sum = 0;
            if (list.length > 0) {
                for (var i = 0; i < list.length; i++) {
                    list[i]['Click'] = "0";
                    sum++;
                }
            }
            if(sum > 0){
                let rs = await this.writeFile(list);
                if (rs) {
                    return true;
                } else {
                    return false;
                }
            }else{
                return false;
            }
        } catch (error) {
            return false;
        }
    }
    async getValueByCondition(linkName) {
        try {
            if (!linkName || linkName == "" || linkName == undefined) {
                return false;
            }
            let alarms = await this.readFile();
            if (alarms.length > 0) {
                for (var i = 0; i < alarms.length; i++) {
                    if (alarms[i]['Show_Name'] == linkName) {
                        return alarms[i];
                    }
                }
                return false;
            } else {
                return false;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async releaseAlarm({ gaojing }) {
        try {
            if (gaojing instanceof Object && Object.keys(gaojing).length > 0) {
                let arr = this.readFile();
                let temp = JSON.parse(JSON.stringify(gaojing));
                let sw = false;
                if (arr instanceof Array && arr.length > 0) {
                    for (var i = 0; i < arr.length; i++) {
                        //如果列表中的Show_Name与参数中的Show_Name相同，则替换，如果没有相同的，则添加
                        if (arr[i]['Show_Name'] == gaojing['Show_Name']) {
                            arr.splice(i, 1);
                            sw = true;
                        }
                    }
                }
                if (sw) {
                    let rs = await this.writeFile(arr);
                    if (rs) {
                        return true;
                    } else {
                        return false;
                    }
                }
                return false;
            }
            return false;
        } catch (error) {
            console.log(error);
            return false;
        }
    }
}

class Poi {
    constructor(fileName) {
        this.fileName = fileName;
        /* this.readFile().then(res => {
            if(res.length == 0){
                console.log("Js_POI.json is init");
                this.initPoi();
            }
        }) */
        this.initPoi()
    }
    async initPoi() {
        try {
            let list = await this.readFile();
            if (!list || list == "" || list == undefined || !(list instanceof Array) || list.length == 0) {
                list = [];
            }
            var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
            let arr = [];
            if (gzcx instanceof Object && Object.keys(gzcx).length > 0) {
                console.log("gzcx was initializationed");
            } else {
                gzcx = { ID: `GZCX0`, Class: "GZ", Name: `BP_POI_GZG0`, Show_Name: "", Mesh: "SM_GZCX", X: 0, Y: 0, Z: "8000000", URL: ``, Build: "1", Visible: "1", Click: "0", Init: "0", R: "1", G: "0", B: "0", Color: "" };
            }
            if (alarms instanceof Array && alarms.length > 0) {
                console.log("gaojing is initializationed");
            } else {
                for (var i = 0; i < 30; i++) {
                    let dt = { ID: ``, Class: "GZ", Name: `BP_POI_GZGJ${i}`, Show_Name: "", Mesh: "SM_GZGJ", X: 0, Y: 0, Z: "8000000", URL: ``, Build: "1", Visible: "1", Click: "0", Init: "0", R: "1", G: "0", B: "0", Color: "" };
                    alarms.push(dt);
                }
            }
            if (stations instanceof Array && stations.length > 0) {
                console.log("stations is initializationed");
            } else {
                for (var i = 0; i < 30; i++) {
                    let dt;
                    if (i == 0) {
                        dt = { "ID": "GDJ0", "Class": "Centre", "Name": `BP_POI_GDJ0`, "Show_Name": "呼和浩特供电公司", "Mesh": "SM_GDJ", "X": "0", "Y": "0", "Z": "8000000", "URL": `${DOMAN}:${PORT}/btgdj`, "Build": "1", "Visible": "0", "Click": "0", "Init": "0", "Color": "Green", "R": "0", "G": "0", "B": "1", "stationId": "-1" }
                    } else {
                        dt = { "ID": `GDJ${i}`, "Class": "Line", "Name": `BP_POI_GDJ${i}`, "Show_Name": "", "Mesh": "SM_GDJ", "X": "0", "Y": "0", "Z": "8000000", "URL": "", "Build": "1", "Visible": "0", "Click": "0", "Init": "0", "Color": "Green", "R": "0", "G": "0", "B": "0", "stationId": "0" }
                    }
                    stations.push(dt);
                }
            }
            arr = [...alarms, ...stations, ...lines, ...boxes];
            arr.push(gzcx);
            let res = await this.writeFile(arr);
        } catch (error) {
            console.log(error)
            return false;
        }
    }
    async readFile() {
        return new Promise((resolve, reject) => {
            try {
                fs.readFile(this.fileName, 'utf-8', (err, data) => {
                    if (err) {
                        resolve([]);
                    } else {
                        let temp;
                        if (data == "" || !data || data == "") {
                            temp = []
                        } else {
                            temp = JSON.parse(data);
                        }
                        if (temp['sites']) {
                            let rs = JSON.parse(JSON.stringify(temp['sites']));
                            resolve(rs);
                        } else {
                            resolve([])
                        }
                    }
                })
            } catch (error) {
                console.log(error);
                resolve([]);
            }
        })
    }
    async writeFile(content) {
        return new Promise((resolve, reject) => {
            try {
                if (!content || content == "" || content == undefined) {
                    content = JSON.stringify({});
                } else {
                    content = JSON.stringify({ sites: content });
                }
                fs.writeFile(this.fileName, content, (err) => {
                    if (err) {
                        resolve(false);
                    } else {
                        resolve(true)
                    }
                })
            } catch (error) {
                console.log(error);
                resolve(false);
            }
        })
    }
    async getValueByCondition({ item, key, value }) {
        try {
            if (!value || value == "" || value == undefined) {
                return false;
            }
            if (!item || item == undefined || item == "") {
                return false;
            }
            if (!key || item == undefined || key == "") {
                return false;
            }
            let list = await this.readFile();
            var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
            var arr;
            if (item == "gaojings") {
                arr = alarms;
            } else if (item == 'stations') {
                arr = stations;
            } else if (item == 'lines') {
                arr = lines;
            } else if (item == 'boxes') {
                arr = boxes;
            } else if (item == 'gzcx') {
                arr = gzcx;
                return gzcx;
            }
            if (arr.length > 0) {
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i][key] == value) {
                        return arr[i];
                    }
                }
                return false;
            } else {
                return false;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    getContent({ alarms, stations, boxes, lines, gzcx }) {
        try {
            if (!(alarms instanceof Array)) {
                alarms = [];
            }
            if (!(stations instanceof Array)) {
                stations = [];
            }
            if (!(boxes instanceof Array)) {
                return false;
            }
            if (!(lines instanceof Array)) {
                return false
            }
            let arr = [...alarms, ...stations, ...lines, ...boxes];
            if (gzcx instanceof Object && Object.keys(gzcx).length > 0) {
                arr.push(gzcx);
            }
            return arr;
        } catch (error) {
            return false;
        }
    }
    getItem(list) {
        let alarms = [];
        let stations = [];
        let lines = [];
        let boxes = [];
        let gzcx;
        for (var i = 0; i < list.length; i++) {
            if (list[i]['Mesh'] == "SM_GDJ") {
                stations.push(list[i]);
            } else if (list[i]['Mesh'] == "SM_GZGJ") {
                alarms.push(list[i]);
            } else if (list[i]['Mesh'] == "SM_Line") {
                lines.push(list[i]);
            }
            else if (list[i]['Mesh'] == "SM_Box") {
                boxes.push(list[i]);
            }
            else if (list[i]['Mesh'] == "SM_GZCX") {
                gzcx = list[i];
            }
        }
        return { alarms, stations, lines, boxes, gzcx }
    }
    async resetClick() {
        try {
            var list = await this.readFile();
            let sum = 0;
            if (list.length > 0) {
                for (var i = 0; i < list.length; i++) {
                    list[i]['Click'] = "0";
                    sum++;
                }

            }
            if(sum > 0){
                let rs = await this.writeFile(list);
                if (rs) {
                    return true;
                } else {
                    return false;
                }
            }else{
                return false;
            }
        } catch (error) {
            return false;
        }
    }
    async settingAlarm({ gaojing }) {
        try {
            let list = await this.readFile();
            var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
            if (gaojing instanceof Object && Object.keys(gaojing).length > 0) {
                let temp = JSON.parse(JSON.stringify(gaojing));
                let sw = false;
                let idx = -1;
                //如果能找到Show_Name相同的线路，就覆盖，否则新建。
                for (var i = 0; i < alarms.length; i++) {
                    if (idx < 0 && alarms[i]['Show_Name'] == "") {
                        idx = i;
                    }
                    if (alarms[i]['Show_Name'] == temp['Show_Name']) {
                        temp['Name'] = alarms[i]['Name'];
                        alarms.splice(i, 1, temp);
                        sw = true;
                        break;
                    }
                }
                //没有找到相同的，就找一条空白的添加，如果没有空白的，就不动。
                if (!sw) {
                    if (idx >= 0) {
                        temp['Name'] = `BP_POI_GZGJ${idx}`;
                        alarms.splice(idx, 1, temp);
                        sw = true;
                    }
                }
                if (sw) {
                    let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
                    let rs = await this.writeFile(arr);
                    if (rs) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async releaseAlarm({ gaojing }) {
        try {
            let list = await this.readFile();
            var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
            if (gaojing instanceof Object && Object.keys(gaojing).length > 0) {
                let temp = JSON.parse(JSON.stringify(gaojing));
                //如果能找到Show_Name相同的线路，就清空。
                for (var i = 0; i < alarms.length; i++) {
                    if (alarms[i]['Show_Name'] == temp['Show_Name']) {
                        temp['X'] = "0";
                        temp['Y'] = "0";
                        temp['Z'] = "8000000";
                        temp['Init'] = "1";
                        temp['Name'] = alarms[i]['Name'];
                        alarms.splice(i, 1, temp);
                        sw = true;
                        break;
                    }
                }
                let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
                let rs = await this.writeFile(arr);
                if (rs) {
                    return true;
                } else {
                    return false;
                }
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async settingStation({ values, remove }) {
        try {
            if (values instanceof Object && Object.keys(values).length > 0) {
                let list = await this.readFile();
                var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
                var sw = false;
                var empty = -1;
                for (var i = 0; i < stations.length; i++) {
                    if (empty < 0 && stations[i]['Show_Name'] == "") {
                        empty = i;
                    }
                    if (stations[i]['stationId'] == values['stationId']) {
                        if (remove) {
                            stations[i]['Show_Name'] = "";
                            stations[i]['X'] = "0";
                            stations[i]['Y'] = "0";
                            stations[i]['Z'] = "8000000";
                            stations[i]['URL'] = "";
                            stations[i]['R'] = "0";
                            stations[i]['G'] = "0";
                            stations[i]['B'] = "0";
                            stations[i]['stationId'] = "0";
                        } else {
                            stations[i]['Show_Name'] = `${values['stationName']}`;
                            stations[i]['URL'] = `${DOMAN}:${PORT}/bdz?stationId=${values['stationId']}`;
                            stations[i]['R'] = `${values['R']}`;
                            stations[i]['G'] = `${values['G']}`;
                            stations[i]['B'] = `${values['B']}`;
                            stations[i]['stationId'] = `${values['stationId']}`;
                            stations[i]['X'] = 3836187.737 * (0 + values['longitude'] - LX) / 0.86915612;
                            stations[i]['Y'] = -7091297.591 * (0 + values['latitude'] - LY) / 1.20283173;
                            stations[i]['Z'] = `${values['Z']}`;
                        }
                        sw = true;
                        break;
                    }
                }
                if (!sw) {
                    if (empty < 0) {
                        empty = list.length;
                    }
                    if (!remove) {
                        stations[empty]['Show_Name'] = `${values['stationName']}`;
                        stations[empty]['URL'] = `${DOMAN}:${PORT}/bdz?stationId=${values['stationId']}`;
                        stations[empty]['R'] = `${values['R']}`;
                        stations[empty]['G'] = `${values['G']}`;
                        stations[empty]['B'] = `${values['B']}`;
                        stations[empty]['stationId'] = `${values['stationId']}`;
                        stations[empty]['X'] = 3836187.737 * (0 + values['longitude'] - LX) / 0.86915612;
                        stations[empty]['Y'] = -7091297.591 * (0 + values['latitude'] - LY) / 1.20283173;
                        stations[empty]['Z'] = `${values['Z']}`;

                    } else {
                        return false;
                    }
                }
                let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
                if (arr instanceof Array) {
                    let rs = await this.writeFile(arr);
                    if (rs) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false
                }
            } else {
                return false;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async emptyStation() {
        try {
            let list = await this.readFile();
            var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
            if (stations.length > 1) {
                for (var i = 1; i < stations.length; i++) {
                    stations[i]['Show_Name'] = "";
                    stations[i]['X'] = "0";
                    stations[i]['Y'] = "0";
                    stations[i]['Z'] = "8000000";
                    stations[i]['URL'] = "";
                    stations[i]['R'] = "0";
                    stations[i]['G'] = "0";
                    stations[i]['B'] = "0";
                    stations[i]['stationId'] = "0";
                }
            }
            let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
            if (arr instanceof Array) {
                let rs = await this.writeFile(arr);
                if (rs) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false
            }
        } catch (error) {
            console.log(error);
            return false;
        }

    }
    setList(item, arr, remove) {
        if (!(item instanceof Object) || Object.keys(item).length == 0) {
            return false;
        }
        if (!(arr instanceof Array) || arr.length == 0) {
            return false;
        }
        var list = JSON.parse(JSON.stringify(arr))
        var sw = false;
        var empty = -1;
        for (var i = 0; i < list.length; i++) {
            if (empty < 0 && list[i]['stationId'] == "0") {
                empty = i;
            }
            if (list[i]['stationId'] == item['stationId']) {
                if (remove) {
                    list[i]['Show_Name'] = "";
                    list[i]['X'] = "0";
                    list[i]['Y'] = "0";
                    list[i]['Z'] = "8000000";
                    list[i]['URL'] = "";
                    list[i]['R'] = "0";
                    list[i]['G'] = "0";
                    list[i]['B'] = "0";
                    list[i]['stationId'] = "0";
                } else {
                    list[i]['Show_Name'] = `${item['stationName']}`;
                    list[i]['URL'] = `${DOMAN}:${PORT}/bdz?stationId=${item['stationId']}`;
                    list[i]['X'] = 3836187.737 * (0 + item['longitude'] - LX) / 0.86915612;
                    list[i]['Y'] = -7091297.591 * (0 + item['latitude'] - LY) / 1.20283173;
                    list[i]['Z'] = `${item['Z']}`;
                    list[i]['R'] = `${item['R']}`;
                    list[i]['G'] = `${item['G']}`;
                    list[i]['B'] = `${item['B']}`;
                    list[i]['stationId'] = `${item['stationId']}`;
                }
                sw = true;
                break;
            }
        }
        if (!sw) {
            if (empty < 0) {
                empty = list.length;
            }
            if (!remove) {
                list[empty]['Show_Name'] = `${item['stationName']}`;
                list[empty]['URL'] = `${DOMAN}:${PORT}/bdz?stationId=${item['stationId']}`;
                list[empty]['R'] = `${item['R']}`;
                list[empty]['G'] = `${item['G']}`;
                list[empty]['B'] = `${item['B']}`;
                list[empty]['stationId'] = `${item['stationId']}`;
                list[empty]['X'] = 3836187.737 * (0 + item['longitude'] - LX) / 0.86915612;
                list[empty]['Y'] = -7091297.591 * (0 + item['latitude'] - LY) / 1.20283173;
                list[empty]['Z'] = `${item['Z']}`;

            } else {
                return false;
            }
        }
        return list;
    }
    async importStation({ arr, remove }) {
        try {
            if (arr instanceof Array && arr.length > 0) {
                let list = await this.readFile();
                var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
                for (var i = 0; i < arr.length; i++) {
                    let temp = this.setList(arr[i], stations, remove);
                    if (temp != false) {
                        stations = temp;
                    }
                }
                let ls = this.getContent({ alarms, stations, boxes, lines, gzcx });
                if (ls instanceof Array) {
                    let rs = await this.writeFile(ls);
                    if (rs) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false
                }

            } else {
                return true;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async settingLines({ values, remove }) {
        try {
            if (values instanceof Object && Object.keys(values).length > 0) {
                let list = await this.readFile();
                var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
                var sw = false;
                var empty = -1;
                for (var i = 0; i < lines.length; i++) {
                    if (empty < 0 && lines[i]['Show_Name'] == "") {
                        empty = i;
                    }
                    if (lines[i]['Show_Name'] == values['Show_Name']) {
                        values['Name'] = `BP_POI_Line${i}`
                        lines.splice(i, 1, values);
                        sw = true;
                        break;
                    }
                }
                //如果没更改就添加
                if (!sw) {
                    if (!remove) {
                        if (empty > 0) {
                            values['Name'] = `BP_POI_Line${empty}`
                            lines.splice(empty, 1, values);
                        } else {
                            values['Name'] = `BP_POI_Line${lines.length}`
                            lines.push(values)
                        }
                    } else {
                        return false;
                    }
                }
                let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
                if (arr instanceof Array) {
                    let rs = await this.writeFile(arr);
                    if (rs) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false
                }
            } else {
                return false;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    //点击线
    async hitLine({ values }) {
        try {
            if (values instanceof Object && Object.keys(values).length > 0) {
                let list = await this.readFile();
                var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
                let sw = false;
                for (var i = 0; i < lines.length; i++) {
                    if (lines[i]['Show_Name'] == values['Show_Name']) {
                        lines[i]['Click'] = values['Click'];
                        sw = true;
                        break;
                    }
                }
                if (sw) {
                    let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
                    if (arr instanceof Array) {
                        let rs = await this.writeFile(arr);
                        if (rs) {
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        return false
                    }
                } else {
                    return false;
                }

            } else {
                return false;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    //单条设置接头盒
    setBoxList(item, arr, linkId) {
        if (!(item instanceof Object) || Object.keys(item).length == 0) {
            return false;
        }
        if (!(arr instanceof Array)) {
            return false;
        }
        var list = JSON.parse(JSON.stringify(arr));
        var sw = false;
        var empty = -1;
        if (list.length === 0) {
            let tmp = {}
            tmp['ID'] = `Box0`;
            tmp['Show_Name'] = `${item['BoxName']}`;
            tmp['URL'] = `${DOMAN}:${PORT}/jth?boxId=${item['ID']}`;
            tmp['X'] = 836187.737 * (0 + item['Longitude'] - LX) / 0.86915612;
            tmp['Y'] = -7091297.591 * (0 + item['Latitude'] - LY) / 1.20283173;
            tmp['Z'] = `${item['Z']}`;
            tmp['boxId'] = `${item['ID']}`;
            tmp['linkId'] = `${linkId}`;
            tmp['Name'] = `BP_POI_Box0`;
            tmp['Init'] = "0";
            tmp['Mesh'] = "SM_Box";
            tmp['Click'] = "0"
            list.push(tmp)
        } else {
            for (var i = 0; i < list.length; i++) {
                if (empty < 0 && list[i]['linkId'] == 0) {
                    empty = i;
                }
                if (list[i]['boxId'] == item['ID']) {
                    list[i]['ID'] = `Box${i}`;
                    list[i]['Show_Name'] = `${item['BoxName']}`;
                    list[i]['URL'] = `${DOMAN}:${PORT}/jth?boxId=${item['ID']}`;
                    list[i]['X'] = 3836187.737 * (0 + item['Longitude'] - LX) / 0.86915612;
                    list[i]['Y'] = -7091297.591 * (0 + item['Latitude'] - LY) / 1.20283173;
                    list[i]['Z'] = `${item['Z']}`;
                    list[i]['boxId'] = `${item['ID']}`;
                    list[i]['linkId'] = `${linkId}`;
                    list[i]['Name'] = `BP_POI_Box${i}`
                    list[i]['Init'] = "0";
                    list[i]['Mesh'] = "SM_Box";
                    list[i]['Click'] = "0";
                    sw = true;
                    break;
                }
            }
            if (!sw) {
                if (empty < 0) {
                    empty = list.length;
                }
                list[empty] = {};
                list[empty]['ID'] = `Box${empty}`;
                list[empty]['boxId'] = item['ID'];
                list[empty]['Show_Name'] = `${item['BoxName']}`;
                list[empty]['URL'] = `${DOMAN}:${PORT}/jth?boxId=${item['ID']}`;
                list[empty]['boxId'] = `${item['ID']}`;
                list[empty]['linkId'] = `${linkId}`;
                list[empty]['X'] = 3836187.737 * (0 + item['Longitude'] - LX) / 0.86915612;
                list[empty]['Y'] = -7091297.591 * (0 + item['Latitude'] - LY) / 1.20283173;
                list[empty]['Z'] = `${item['Z']}`;
                list[empty]['Name'] = `BP_POI_Box${empty}`
                list[empty]['Init'] = "0";
                list[empty]['Mesh'] = "SM_Box";
                list[empty]['Click'] = "0";
            }
        }
        return list;
    }
    async settingBoxes({ arr, linkId }) {
        try {
            if (!(arr instanceof Array) || arr.length == 0) {
                return false;
            }
            if (!linkId || linkId <= 0) {
                return false;
            }
            let list = await this.readFile();
            var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
            if (boxes.length > 0) {
                for (var i = boxes.length - 1; i >= 0; i--) {
                    if (boxes[i]['linkId'] == linkId) {
                        let obj = boxes[i];
                        obj.linkId = 0;
                        obj['X'] = 0;
                        obj['Y'] = 0;
                        obj['Z'] = "8000000";
                        obj['Show_Name'] = "";
                        obj['boxId'] = 0;
                        obj['URL'] = "";
                        obj['Init'] = "1";
                        obj['Mesh'] = "SM_Box";
                        obj['Click'] = "0";
                        boxes.splice(i, 1, obj);
                    }
                }
            }
            for (var i = 0; i < arr.length; i++) {
                let temp = this.setBoxList(arr[i], boxes, linkId);
                if (temp != false) {
                    boxes = temp;
                }
            }
            let res = this.getContent({ alarms, stations, boxes, lines, gzcx });
            if (res instanceof Array) {
                let rs = await this.writeFile(res);
                if (rs) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async clearBoxes({ linkId }) {
        try {
            if (!linkId || linkId <= 0) {
                return false;
            }
            let list = await this.readFile();
            var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
            if (boxes.length > 0) {
                for (var i = boxes.length - 1; i >= 0; i--) {
                    if (boxes[i]['linkId'] == linkId) {
                        boxes.splice(i, 1);
                    }
                }
                let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
                if (arr instanceof Array) {
                    let rs = await this.writeFile(arr);
                    if (rs) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false
                }
            } else {
                return;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async setGzcx(gaojing) {
        try {
            if (gaojing instanceof Object && Object.keys(gaojing).length > 0) {
                let list = await this.readFile();
                var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
                gzcx['Show_Name'] = gaojing.linkName;
                gzcx['X'] = gaojing.X;
                gzcx['Y'] = gaojing.Y;
                gzcx['Z'] = gaojing.Z;
                gzcx['URL'] = gaojing.URL;
                gzcx['Click'] = "1";
                gzcx['Init'] = "0";
                let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
                if (arr instanceof Array) {
                    let rs = await this.writeFile(arr);
                    if (rs) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false
                }
            } else {
                return false;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async jcGzcx(gaojing) {
        try {
            if (gaojing instanceof Object && Object.keys(gaojing).length > 0) {
                let list = await this.readFile();
                var { alarms, stations, lines, boxes, gzcx } = this.getItem(list);
                gzcx['Init'] = "0";
                let arr = this.getContent({ alarms, stations, boxes, lines, gzcx });
                if (arr instanceof Array) {
                    let rs = await this.writeFile(arr);
                    if (rs) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false
                }
            } else {
                return false;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
}

class Updata {
    constructor(fileName) {
        this.fileName = fileName;
        this.initUpdata()
    }
    async initUpdata() {
        try {
            let str = JSON.stringify({ sites: { Updata: "0" } })
            fs.writeFile(this.fileName, str, (err) => {
                if (err) {
                    return false;
                } else {
                    return true;
                }
            })
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    async readFile() {
        return new Promise((resolve, reject) => {
            try {
                fs.readFile(this.fileName, 'utf-8', (err, data) => {
                    if (err) {
                        return { sites: { Updata: "0" } }
                    } else {
                        if (data == "") {
                            data = JSON.stringify({ sites: { Updata: "0" } })
                        }
                        let temp = JSON.parse(data);
                        return temp;
                    }
                })
            } catch (error) {
                return { sites: { Updata: "0" } };
            }

        })
    }
    async writeFile(content) {
        return new Promise((resolve, reject) => {
            try {
                if (!(content instanceof Object) || Object.keys(content).length == 0) {
                    return false;
                }
                let str = JSON.stringify(content);
                fs.writeFile(this.fileName, str, (err) => {
                    if (err) {
                        return false;
                    } else {
                        return true;
                    }
                });
                setTimeout(() => {
                    fs.writeFile(this.fileName, JSON.stringify({ sites: { Updata: "0" } }), err => { })
                }, 500)
            } catch (error) {
                console.log(error);
                return false;
            }
        })

    }
    async update({ num, delay }) {
        try {
            var content;
            if (num == 1) {
                content = { sites: { Updata: "1" } }
            } else {
                content = { sites: { Updata: "0" } };
            }
            if (delay == undefined || delay == "" || delay <= 0) {
                delay = 500;
            }
            let rs = await this.writeFile(content);
            return rs;
        } catch (error) {
            console.log(error);
        }
    }
}
class Nodes {
    constructor() {

    }
    static getFileName(linkId) {
        return `${DATA_PATH}Js_Node${linkId}.json`;
    }
    static async readFile(linkId) {
        return new Promise((resolve, reject) => {
            try {
                if (!linkId || linkId < 0) {
                    return false;
                }
                let fileName = this.getFileName(linkId)
                fs.readFile(fileName, 'utf-8', (err, data) => {
                    if (err) {
                        resolve([]);
                    } else {
                        if (data == "") {
                            data = JSON.stringify({ sites: [] });
                        }
                        let temp = JSON.parse(data);
                        if (temp['sites']) {
                            let rs = JSON.parse(JSON.stringify(temp['sites']));
                            resolve(rs)
                        } else {
                            resolve([]);
                        }
                    }
                })
            } catch (error) {
                resolve([])
            }
        })
    }
    static async writeFile(linkId, content) {
        return new Promise((resolve, reject) => {
            try {
                if (!linkId || linkId < 0) {
                    resolve(false);
                }
                if (!content || content == "" || content == undefined || !(content instanceof Array)) {
                    resolve(false);
                }
                var fileName = this.getFileName(linkId);
                var str = JSON.stringify({ sites: content });
                fs.writeFile(fileName, str, err => {
                    if (err) {
                        resolve(false);
                    } else {
                        resolve(true);
                    }
                })
            } catch (error) {
                console.log(error);
                resolve(false);
            }
        })
    }
    static async eraseFile(linkId) {
        return new Promise((resolve, reject) => {
            try {
                if (!linkId || linkId < 0) {
                    return false;
                }
                let fileName = this.getFileName(linkId);
                fs.unlink(fileName, err => {
                    if (err) {
                        resolve(false);
                    } else {
                        resolve(true)
                    }
                })
            } catch (error) {
                console.log(error);
                return false;
            }
        })
    }
    static async createLine({ linkId, linkName, arr }) {
        try {
            if (!linkId || linkId <= 0) {
                return false;
            }
            if (!linkName || linkName == "" || linkName == undefined) {
                return false;
            }
            if (!(arr instanceof Array) || arr.length == 0) {
                return false;
            }
            var list = [];
            for (var i = 0; i < arr.length; i++) {
                let obj;
                if (arr[i]['nodeType'] == "WM_Well") {
                    obj = { ID: `L${linkId}N${i}`, class: "Node", Name: `BP_Node_L${linkId}N${i}`, Show_Name: linkName, Mesh: arr[i]['nodeType'], X: 3836187.737 * (0 + arr[i]['longitude'] - LX) / 0.86915612, Y: -7091297.591 * (0 + arr[i]['latitude'] - LY) / 1.20283173, Z: arr[i]['Z'], Build: "1", Click: "0", R: arr[i]['R'], G: arr[i]['G'], B: arr[i]['B'], opticalId: arr[i]['opticalId'] };
                } else {
                    obj = { ID: `L${linkId}N${i}`, class: "Node", Name: `BP_Node_L${linkId}N${i}`, Show_Name: linkName, Mesh: arr[i]['nodeType'], X: 3836187.737 * (0 + arr[i]['longitude'] - LX) / 0.86915612, Y: -7091297.591 * (0 + arr[i]['latitude'] - LY) / 1.20283173, Z: arr[i]['Z'], Build: "1", Click: "0", R: arr[i]['R'], G: arr[i]['G'], B: arr[i]['B'], opticalId: arr[i]['opticalId'] };
                }
                list.push(obj);
            }
            var rs = await this.writeFile(linkId, list);
            return rs;
        } catch (error) {
            console.log(error);
            return false;
        }
    }
    //model=1为设置告警，R为0.2，否则为原本颜色
    static async changeColor({ linkId, linkName, num, model,color }) {
        try {
            var R,G,B;
            if (!linkId || linkId <= 0 || linkId == undefined) {
                return false;
            }
            if (num < 0 || num == undefined) {
                return false;
            }
            if(color == undefined || color == "" || color == null || color == 0 || !color || color == "0"){
                R = "0.2";
                G = "0";
                B = "0"
            }else{
                R = "0";
                G = "0.2";
                B = "0";
            }
            var start = 0;
            var opticals = await getOptical({ linkName });
            if (!opticals) {
                return false;
            }
            let list = await this.readFile(linkId);
            if (!list || list.length == 0 || list == undefined) {
                return false;
            }
            for (var j = 0; j < list.length; j++) {
                if (num == list[j]['opticalId']) {
                    start = j;
                    break;
                }
            }
            if (model == 1) {
                list[start]['R'] = R;
                list[start]['G'] = G;
                list[start]['B'] = B;
                if (list[start + 1]) {
                    list[start + 1]['R'] = R;
                    list[start + 1]['G'] = G;
                    list[start + 1]['B'] = B;
                }
                if (list[start + 2]) {
                    list[start + 2]['R'] = R;
                    list[start + 2]['G'] = G;
                    list[start + 2]['B'] = B;
                }
            } else {
                let sw1 = false;
                let sw2 = false;
                let sw3 = false;
                for (var i = 0; i < opticals.length; i++) {
                    if (list[start]['opticalId'] == opticals[i]['opticalId']) {
                        sw1 = true;
                        list[start]['R'] = opticals[i]['R'];
                        list[start]['G'] = opticals[i]['G'];
                        list[start]['B'] = opticals[i]['B'];
                    }
                    if (list[start + 1]) {
                        if (list[start + 1]['opticalId'] == opticals[i]['opticalId']) {
                            sw2 = true;
                            list[start + 1]['R'] = opticals[i]['R'];
                            list[start + 1]['G'] = opticals[i]['G'];
                            list[start + 1]['B'] = opticals[i]['B'];
                        }
                    }
                    if (list[start + 2]) {
                        if (list[start + 2]['opticalId'] == opticals[i]['opticalId']) {
                            sw3 = true;
                            list[start + 2]['R'] = opticals[i]['R'];
                            list[start + 2]['G'] = opticals[i]['G'];
                            list[start + 2]['B'] = opticals[i]['B'];
                        }
                    }
                    if (sw1 && sw2 && sw3) {
                        break;
                    }
                }
            }
            let rs = await this.writeFile(linkId, list);
            if (rs) {
                return true;
            } else {
                return false;
            }
        } catch (error) {
            console.log(error);
            return false;
        }
    }
}
module.exports = {
    Gzgj,
    Poi,
    Updata,
    Nodes
}